using homework_2_test_first_development.Enums;
using homework_2_test_first_development.Models;

namespace homework_2_test_first_development.Validators;

internal static class BarcodeValidator
{
    public static char Seperator => '-';
    public static int Maximum => 99;

    public static ValidationResult ValidateBarcodes(IEnumerable<string> selectedBarcodes, IEnumerable<Product> products)
    {
        foreach (var item in selectedBarcodes)
        {
            if (string.IsNullOrEmpty(item))
                return new ValidationResult { Error = ErrorType.InvalidBarcode };

            string barcode = string.Empty;
            string amount = string.Empty;

            if (item.Contains(Seperator))
            {
                var barcodeParts = item.Split(Seperator);

                barcode = barcodeParts[0];
                amount = barcodeParts[1];

                if (string.IsNullOrEmpty(amount) || amount.Any(c => !Char.IsDigit(c)))
                    return new ValidationResult { Error = ErrorType.InvalidBarcode };

                int number = int.Parse(amount);

                if (number > Maximum)
                    return new ValidationResult { Error = ErrorType.InvalidBarcode };
            }
            else
            {
                barcode = item;
            }

            if (string.IsNullOrEmpty(barcode) || barcode.Any(c => !(Char.IsDigit(c) || Char.IsUpper(c))))
                return new ValidationResult { Error = ErrorType.InvalidBarcode };

            if (!products.Where(p => p.Barcode == barcode).Any())
                return new ValidationResult { Error = ErrorType.ProductNotFound, Barcode = barcode };
        }

        return new ValidationResult() { Error = ErrorType.Valid };
    }
}
